package com.shxc.smarttrade.old.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.dialogactivity.StatementDialogActivity;
import com.shxc.smarttrade.old.bean.OpenAccountStatus;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.tigerwit.activity.TigerwitOpenAccountActivity;
import com.shxc.smarttrade.utils.ToastUtils;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/11/2.
 */

public class SelectBrokeOpenAccountActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.incloude_roll_one)
    AutoLinearLayout incloudeRollOne;
    @BindView(R.id.tv_roll_one)
    TextView tvRollOne;
    @BindView(R.id.iv_roll_one)
    ImageView ivRollOne;

    @BindView(R.id.incloude_roll_two)
    AutoLinearLayout incloudeRollTwo;
    @BindView(R.id.tv_roll_two)
    TextView tvRollTwo;
    @BindView(R.id.iv_roll_two)
    ImageView ivRollTwo;

    @BindView(R.id.tv_err_status)
    TextView tvErrorStatus;//审核失败状态返回值
    @BindView(R.id.tv_open_account_explain)
    TextView tvOpenAccountExplain;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.tv_open_tiger)
    TextView tvOpenTiger;

    private boolean isChecked = true;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String registerURL = (String) msg.obj;
//                    Intent intent = new Intent(SelectBrokeOpenAccountActivity.this, OpenAccountActivity.class);
                    Intent intent = new Intent(SelectBrokeOpenAccountActivity.this, TigerwitOpenAccountActivity.class);
                    intent.putExtra("url", registerURL);
                    startActivity(intent);
                    break;
                case 1:
                    List<OpenAccountStatus.DataBean> dataBean = (List<OpenAccountStatus.DataBean>) msg.obj;
//                    if (dataBean.get(0).getStatus() == 3) {
//                        tvErrorStatus.setText("审核失败原因：" + dataBean.get(0).getMessage() + "，请重新提交审核。");
//                    }
                    switch (dataBean.get(0).getStatus()) {
                        case 0://未开户
                            tvOpenTiger.setText("前往经纪商开户");
                            tvOpenTiger.setEnabled(true);
                            break;
                        case 1://开户中
                            tvOpenTiger.setText("经纪商审核中");
                            tvOpenTiger.setEnabled(false);
                            break;
                        case 2://开户成功
                            tvOpenTiger.setText("您已开通此账户");
                            tvOpenTiger.setEnabled(false);
                            break;
                        case 3://审核失败
                            tvOpenTiger.setText("请重新提交审核");
                            tvOpenTiger.setEnabled(true);
                            tvErrorStatus.setText("审核失败原因：" + dataBean.get(0).getMessage() + "，请重新提交审核。");
                            break;
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_broke_open_account);
        ButterKnife.bind(this);
        initView();
        initListener();
    }



    private void initListener() {
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                SelectBrokeOpenAccountActivity.this.isChecked = isChecked;
            }
        });
    }

    private void initData() {
        getOpenAccountStatus();
    }

    private void initView() {

        tvCenter.setText("选择经纪商");

    }

    @OnClick({R.id.rl_left, R.id.ll_roll_one, R.id.ll_roll_two, R.id.tv_open_account_explain, R.id.tv_open_tiger, R.id.kunlun_textview})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.ll_roll_one:
                if (incloudeRollOne.isShown()) {
                    incloudeRollOne.setVisibility(View.GONE);
                    tvRollOne.setText("展开");
                    ivRollOne.setImageResource(R.mipmap.down_icon2);
                } else {
                    incloudeRollOne.setVisibility(View.VISIBLE);
                    tvRollOne.setText("收起");
                    ivRollOne.setImageResource(R.mipmap.up_icon2);
                }
                break;
            case R.id.ll_roll_two:

                if (incloudeRollTwo.isShown()) {
                    incloudeRollTwo.setVisibility(View.GONE);
                    tvRollTwo.setText("展开");
                    ivRollTwo.setImageResource(R.mipmap.down_icon2);
                } else {
                    incloudeRollTwo.setVisibility(View.VISIBLE);
                    tvRollTwo.setText("收起");
                    ivRollTwo.setImageResource(R.mipmap.up_icon2);
                }
                break;
            case R.id.tv_open_account_explain:
                showExplain();
                break;
            case R.id.tv_open_tiger:
                if (isChecked) {//同意声明->继续
                    getTangerForeURL();
                } else {
                    showToast("未同意开户声明");
                }
                break;
            case R.id.kunlun_textview:
                ToastUtils.showToast("昆仑国际（KVB）即将上线，敬请期待~");
                break;
        }
    }

    private void showExplain() {

        JumpTo(StatementDialogActivity.class);

//        View view = View.inflate(this, R.layout.pop_open_account_explain_layout, null);
//        TextView btnYes = (TextView) view.findViewById(R.id.btn_yes);
//        TextView btnNo = (TextView) view.findViewById(R.id.btn_no);
//
//
//        final PopupWindow popupWindow = BaseView.showPopupWindow(view, this, R.layout.activity_select_broke_open_account, Gravity.CENTER);
//        btnYes.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popupWindow.dismiss();
//                checkBox.setChecked(true);
//            }
//        });
//        btnNo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popupWindow.dismiss();
//            }
//        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean isFirstInSelectBroke = SpUtils.getBoolean(SelectBrokeOpenAccountActivity.this, "isFirstInSelectBroke", false);
                if (!isFirstInSelectBroke) {
                    showExplain();
                    SpUtils.putBoolean(SelectBrokeOpenAccountActivity.this, "isFirstInSelectBroke", true);
                }
            }
        }, 500);
        initData();
    }


    /**
     * 获取老虎外汇链接
     */
    private void getTangerForeURL() {
        showShortDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessTokenss);
        map.put("userId", userIdss);
        map.put("phone", telePhoness);
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.ACCOUNT_FRAGMENT_REGISTERURL, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast(getString(R.string.net_error));
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                dismissShortDialog();
                if (response == null || new JsonParser().parse(response).isJsonNull()) {
                    showToast(getString(R.string.data_error));
                    return;
                }
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                String errCode = "";
                String errMsg = "";
                if (!jsonObject.get("err_code").isJsonNull())
                    errCode = jsonObject.get("err_code").getAsString();
                if (!jsonObject.get("err_msg").isJsonNull())
                    errMsg = jsonObject.get("err_msg").getAsString();
                if (errCode.equals("0")) {
                    JsonObject data = jsonObject.get("data").getAsJsonObject();
                    String registerURL = "";
                    if (!data.get("registerURL").isJsonNull())
                        registerURL = data.get("registerURL").getAsString();
                    Message msg = Message.obtain();
                    msg.what = 0;
                    msg.obj = registerURL;
                    handler.sendMessage(msg);
                } else {
                    showToast(errMsg);
                }
            }
        });
    }


    private void getOpenAccountStatus() {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", accessTokenss);
        map.put("userId", userIdss);
        MyOkHttpUtils.getServiceDatas(this, map, URLContents.SELECT_ACCOUNT_USEROPEN, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
            }

            @Override
            public void success(String response, int id) {

                if (response != null) {
                    Gson gson = new Gson();
                    OpenAccountStatus os = gson.fromJson(response, OpenAccountStatus.class);
                    if (os.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 1;
                        msg.obj = os.getData();
                        handler.sendMessage(msg);

                    } else
                        showToast(os.getErr_msg());
                }
            }
        });
    }


    public void JumpTo(Class cla) {
        Intent intent = new Intent(this, cla);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_from_bottom, R.anim.slide_notmove);
    }
}
